import logging
from logging.handlers import TimedRotatingFileHandler
import os

# 确保日志层次结构正确配置
def setup_logger(log_dir, backup_days=7, log_level='INFO'):
    """
    设置全局日志系统
    
    Args:
        log_dir: 日志文件目录
        backup_days: 日志保留天数
        log_level: 日志级别
    
    Returns:
        配置好的根logger
    """
    # 确保日志目录存在
    os.makedirs(log_dir, exist_ok=True)
    
    # 获取日志级别
    level_map = {
        'DEBUG': logging.DEBUG,
        'INFO': logging.INFO,
        'WARNING': logging.WARNING,
        'WARN': logging.WARNING,
        'ERROR': logging.ERROR,
        'CRITICAL': logging.CRITICAL
    }
    log_level_value = level_map.get(log_level.upper(), logging.INFO)
    
    # 配置根logger 'indsrv'
    root_logger = logging.getLogger('indsrv')
    root_logger.setLevel(log_level_value)
    root_logger.propagate = False  # 防止日志向上传播到root logger
    
    # 清空现有处理器
    if root_logger.handlers:
        for handler in root_logger.handlers[:]:
            handler.close()
            root_logger.removeHandler(handler)
    
    # 创建日志格式
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    
    # 文件日志处理器
    log_file = os.path.join(log_dir, 'indsrv.log')
    file_handler = TimedRotatingFileHandler(
        log_file, when='midnight', interval=1, 
        backupCount=backup_days, encoding='utf-8'
    )
    file_handler.suffix = '%Y-%m-%d.log'
    file_handler.setLevel(log_level_value)
    file_handler.setFormatter(formatter)
    
    # 控制台日志处理器
    console_handler = logging.StreamHandler()
    console_handler.setLevel(log_level_value)
    console_handler.setFormatter(formatter)
    
    # 添加处理器到根logger
    root_logger.addHandler(file_handler)
    root_logger.addHandler(console_handler)
    
    print(f"Logger system initialized with level: {log_level}, backup days: {backup_days}")
    return root_logger


def get_logger(module_name):
    """
    获取指定模块的logger实例，自动继承根logger的配置
    
    Args:
        module_name: 模块名称，如'utils', 'file_operations'等
    
    Returns:
        配置好的logger实例
    """
    # 创建或获取子logger
    logger = logging.getLogger(f'indsrv.{module_name}')
    # 默认情况下propagate=True，会将日志传递给父logger的处理器
    # 所以不需要为每个子logger添加处理器
    
    return logger